/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.trader.beans.java;

import ca.trader.beans.enterprise.SaleBeanLocal;
import ca.trader.except.UserNotAuthenticatedException;
import ca.trader.logger.TraderLogger;
import ca.trader.sale.Sale;
import ca.trader.utils.HttpUtils;
import java.util.List;
import javax.servlet.http.HttpSession;

/**
 * A regular JavaBean to look up the sales created by a certain user. The
 * options to look up sales are: - by user ID (ID of the sale created by the
 * user) the authenticated user
 *
 * To find a sales by ID, call the setUserId method To find the authenticated
 * user, call the setSession method
 *
 * To set the page number, use the setPageNumber method
 *
 * @author Ahsan
 */
public class UserSalesLookupBean
{

	 private static final String _className = UserSalesLookupBean.class.getName();
	 private List<Sale> saleList;
	 private int saleCount;
	 private int pageNumber = -1;
	 private boolean foundResults = false;
	 private Integer sellerID;
	 
	 /**
	  * Sets the session object and looks up the authenticated user
	  *
	  * @param sess the session object
	  */
	 public void setSession(HttpSession sess)
	 {
		  final String _methodName = "setSession";

		  TraderLogger.logMethodEntry(_className, _methodName);
		  TraderLogger.logInfo(_className, _methodName, "Trying to find sales by authenticated user");

		  saleList = null;
		  foundResults = false;

		  if (pageNumber == -1)
		  {
			   TraderLogger.logWarning(_className, _methodName, "Page number is not set.  Exiting");

			   TraderLogger.logMethodExit(_className, _methodName);
			   return;
		  }

		  try
		  {

			   // Get the authenticated user id
			   sellerID = HttpUtils.getAuthenticatedUserID(sess);


			   setSalesBySeller(sellerID);
		  }
		  // If no authenticated user is found
		  catch (UserNotAuthenticatedException ex)
		  {
			   TraderLogger.logInfo(_className, _methodName, "No authenticated user exists.");
		  }
		  catch (Exception ex)
		  {
			   TraderLogger.logSevere(_className, _methodName, "Unknown exception ", ex);
		  }

		  TraderLogger.logMethodExit(_className, _methodName);
	 }

	 /**
	  * Finds a user by userID
	  *
	  * @param sID the user id
	  */
	 public void setUserId(String sID)
	 {

		  final String _methodName = "setUserId";

		  TraderLogger.logMethodEntry(_className, _methodName);


		  saleList = null;
		  foundResults = false;

		  if (pageNumber == -1)
		  {
			   TraderLogger.logWarning(_className, _methodName, "Page number is not set.  Exiting");

			   TraderLogger.logMethodExit(_className, _methodName);
			   return;
		  }

		  TraderLogger.logInfo(_className, _methodName, "Finding sales for user with ID: " + sID);

		  // if the ID is null
		  if (sID == null)
		  {
			   TraderLogger.logInfo(_className, _methodName, "User ID is null. Doing nothing");
		  }
		  else
		  {
			   try
			   {
				    sellerID = Integer.parseInt(sID);

				    setSalesBySeller(sellerID);

			   }
			   // If the id is not a number
			   catch (NumberFormatException nfe)
			   {
				    TraderLogger.logWarning(_className, _methodName, "ID is not an integer.  Doing nothing.");
			   }
			   // Other exception
			   catch (Exception e)
			   {
				    TraderLogger.logSevere(_className, _methodName, "Unknown exception ", e);
			   }
		  }

		  TraderLogger.logMethodExit(_className, _methodName);
	 }

	 private void setSalesBySeller(Integer sellerID)
	 {

		  final String _methodName = "setSalesBySeller";

		  TraderLogger.logMethodEntry(_className, _methodName);


		  try
		  {
			   SaleBeanLocal saleBean = BeanUtils.getSaleBean();
			   saleCount = saleBean.getSaleCountBySellerID(sellerID);

			   if (saleCount == 0)
			   {
				    TraderLogger.logInfo(_className, _methodName, "No sales found for the user.");
			   }
			   else
			   {
				    TraderLogger.logInfo(_className, _methodName, "Found total sale count for user: " + saleCount);
				    saleList = saleBean.getSalesBySellerID(sellerID, BeanConsts.SALES_PER_PAGE * (pageNumber - 1), BeanConsts.SALES_PER_PAGE);

				    if (!saleList.isEmpty())
				    {
						foundResults = true;

						TraderLogger.logInfo(_className, _methodName, "Found sales for the page.  Count: " + saleList.size());
				    }
			   }
		  }
		  catch (Exception ex)
		  {
			   TraderLogger.logSevere(_className, _methodName, "Unknown exception ", ex);
		  }

		  TraderLogger.logMethodExit(_className, _methodName);
	 }

	 /**
	  *
	  * @return if the user was found
	  */
	 public boolean isResultsFound()
	 {
		  //  return user != null;
		  return foundResults;
	 }

	 public void setPageNumber(String sPageNumber)
	 {
		  final String _methodName = "setPageNumber";
		  TraderLogger.logWarning(_className, _methodName, "Setting page number: " + sPageNumber);
		  try
		  {
			   pageNumber = Integer.parseInt(sPageNumber);
		  }
		  catch (NumberFormatException ex)
		  {
			   pageNumber = -1;
			   TraderLogger.logWarning(_className, "setPageNumber", "Error setting page number: " + sPageNumber);
		  }
	 }

	 public int getTotalUserSaleCount()
	 {
		  if (!foundResults)
		  {
			   throw new IllegalStateException("No sales have been found.");
		  }
		  return saleCount;
	 }

	 public List<Sale> getSaleList()
	 {

		  if (!foundResults)
		  {
			   throw new IllegalStateException("No sales have been found.");
		  }
		  return saleList;
	 }

	 public int getPageSaleCount()
	 {
		  if (!foundResults)
		  {
			   throw new IllegalStateException("No sales have been found.");
		  }
		  return saleList.size();
	 }

	 public String getPageNumber()
	 {

		  if (!foundResults)
		  {
			   throw new IllegalStateException("No sales have been found.");
		  }

		  return pageNumber + "";
	 }

	 public String getTotalPageNumbers()
	 {
		  if (!foundResults)
		  {
			   throw new IllegalStateException("No sales have been found.");
		  }
		  
		  TraderLogger.logInfo(_className, "getTotalPageNumbers", "Total page numbers: " + ((int) Math.ceil(((double) saleCount) / ((double) BeanConsts.SALES_PER_PAGE))) + "");

		  return ((int) Math.ceil(((double) saleCount) / ((double) BeanConsts.SALES_PER_PAGE))) + "";
	 }

	 public String getUserId()
	 {
		  if (!foundResults)
		  {
			   throw new IllegalStateException("No sales have been found.");
		  }
		  
		  return sellerID + "";
	 }
}
